import time, os, sys, network
import socket
import _thread

from media.sensor import *
from media.display import *
from media.media import *

def setup_ap():
    """设置AP模式"""
    print("[测试] 初始化AP模式...")
    ap = network.WLAN(network.AP_IF)
    ap.active(True)
    ap.config(ssid="K230-Camera", key="12345678")
    print("[测试] AP模式已启动，IP:", ap.ifconfig()[0])
    return ap

def websocket_server():
    """简单的WebSocket服务器"""
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.bind(('0.0.0.0', 6001))
        s.listen(5)
        print("[测试] WebSocket服务器启动成功，监听端口6001")
        while True:
            conn, addr = s.accept()
            print("[测试] 新客户端连接:", addr)
            conn.send(b"Welcome to K230 WebSocket Server")
            conn.close()
    except Exception as e:
        print("[测试] WebSocket服务器错误:", e)

def main():
    try:
        # 设置AP模式
        ap = setup_ap()
        
        # 启动WebSocket服务器
        print("[测试] 启动WebSocket服务器...")
        _thread.start_new_thread(websocket_server, ())
        
        # 配置媒体管理器
        print("[测试] 配置媒体管理器...")
        config = k_vb_config()
        config.max_pool_cnt = 1
        config.comm_pool[0].blk_size = 1024
        config.comm_pool[0].blk_cnt = 1
        config.comm_pool[0].mode = VB_REMAP_MODE_NOCACHE
        ret = MediaManager._config(config)
        if not ret:
            raise RuntimeError("缓冲区配置失败")
        print("[测试] 媒体管理器配置成功")
        
        # 初始化媒体管理器
        print("[测试] 初始化媒体管理器...")
        MediaManager.init()
        print("[测试] 媒体管理器初始化成功")
        
        # 初始化传感器
        print("[测试] 初始化传感器...")
        sensor = Sensor(id=2)
        sensor.reset()
        
        # 设置通道0的输出尺寸为640x480
        print("[测试] 设置传感器分辨率...")
        sensor.set_framesize(Sensor.VGA, chn=CAM_CHN_ID_0)
        # 设置通道0的输出像素格式为RGB888
        sensor.set_pixformat(Sensor.RGB888, chn=CAM_CHN_ID_0)
        print("[测试] 传感器参数设置完成")
        
        # 启动传感器
        print("[测试] 启动传感器...")
        sensor.run(1)
        print("[测试] 传感器启动成功")
        
        # 测试捕获图像
        print("[测试] 开始捕获图像...")
        for i in range(5):
            print(f"[测试] 捕获第{i+1}帧...")
            img = sensor.snapshot(chn=CAM_CHN_ID_0)
            print(f"[测试] 第{i+1}帧捕获成功")
            time.sleep_ms(500)
            os.exitpoint()
        
        print("[测试] 测试完成")
        
    except Exception as e:
        print(f"[测试] 错误: {e}")
    finally:
        print("[测试] 清理资源...")
        # 停止传感器
        try:
            if 'sensor' in locals() and sensor:
                sensor.stop()
                print("[测试] 传感器已停止")
        except Exception as e:
            print(f"[错误] 停止传感器失败: {e}")
        
        # 释放媒体缓冲区
        try:
            MediaManager.deinit()
            print("[测试] 媒体管理器已释放")
        except Exception as e:
            print(f"[错误] 释放媒体管理器失败: {e}")
        
        print("[测试] 程序结束")

if __name__ == "__main__":
    main()